package org.itboys.weixin.tools;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.lang3.StringUtils;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.utils.json.JsonUtils;
import org.itboys.weixin.constant.WeixinConstants;
import org.itboys.weixin.dto.SendArticle;
import org.itboys.weixin.dto.WeixinResult;
import org.itboys.weixin.entity.SendWeixinMessageDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;

/**
 * 微信发送消息相关
 * @author ChenJunhui
 *
 */
public class WeixinSendUtils {

	private static  Logger logger = LoggerFactory.getLogger(WeixinSendUtils.class);
	
	/**
	 * 发送文本信息给客户
	 * @param appId
	 * @param appSecret
	 * @param message
	 * @return  -1 调用接口失败 -2 微信接口返回错误编码 0 异常 1 OK
	 */
	public static int sendMessage(String appId,String appSecret,String weixinUserId,String content){
		Map<String, Object> resultMap = new HashMap<String, Object>(5);
		resultMap.put("touser", weixinUserId);
		resultMap.put("msgtype", "text");
		Map<String, Object> text = new HashMap<String, Object>(2);
		text.put("content", content);
		resultMap.put("text", text);
		String message = JsonUtils.objectToString(resultMap);
		return doSendMessage(appId, appSecret, message);
	}

	/**
	 * 发送多图文信息给客户
	 * @param appId
	 * @param appSecret
	 * @param articles
	 * @return  -1 调用接口失败 -2 微信接口返回错误编码 0 异常 1 OK
	 */
	public static int sendMessage(String appId,String appSecret,String weixinUserId,List<SendArticle> articles){
		Map<String, Object> result = new HashMap<String, Object>(5);
		result.put("touser", weixinUserId);
		result.put("msgtype", "news");
		Map<String, Object> news = new HashMap<String, Object>(2);
		news.put("articles", articles);
		result.put("news", news);
		String message = JsonUtils.objectToString(result);
		return doSendMessage(appId, appSecret, message);
	}
	
	/**
	 * 发送图片消息
	 * @param appId
	 * @param appSecret
	 * @param weixinUserId
	 * @param mediaId 多媒体ID
	 * @return  -1 调用接口失败 -2 微信接口返回错误编码 0 异常 1 OK
	 */
	public static int sendImageMessage(String appId,String appSecret,String weixinUserId,String mediaId){
		Map<String, Object> result = new HashMap<String, Object>(5);
		result.put("touser", weixinUserId);
		result.put("msgtype", "image");
		Map<String, Object> image = new HashMap<String, Object>(2);
		image.put("media_id", mediaId);
		result.put("image", image);
		String message = JsonUtils.objectToString(result);
		return doSendMessage(appId, appSecret, message);
	}
	
	/**
	 * 发送语言消息
	 * @param appId
	 * @param appSecret
	 * @param weixinUserId
	 * @param mediaId 多媒体ID
	 * @return  -1 调用接口失败 -2 微信接口返回错误编码 0 异常 1 OK
	 */
	public static int sendVoiceMessage(String appId,String appSecret,String weixinUserId,String mediaId){
		Map<String, Object> result = new HashMap<String, Object>(5);
		result.put("touser", weixinUserId);
		result.put("msgtype", "voice");
		Map<String, Object> voice = new HashMap<String, Object>(2);
		voice.put("media_id", mediaId);
		result.put("voice", voice);
		String message = JsonUtils.objectToString(result);
		return doSendMessage(appId, appSecret, message);
	}
	
	/**
	 * 发送视频消息
	 * @param appId
	 * @param appSecret
	 * @param weixinUserId
	 * @param mediaId 多媒体ID
	 * @param title 视频标题 可空
	 * @param title description 视频描述 可空
	 * @return  -1 调用接口失败 -2 微信接口返回错误编码 0 异常 1 OK
	 */
	public static int sendVideoMessage(String appId,String appSecret,String weixinUserId,String mediaId,String title,String description){
		Map<String, Object> result = new HashMap<String, Object>(5);
		result.put("touser", weixinUserId);
		result.put("msgtype", "video");
		Map<String, Object> video = new HashMap<String, Object>(2);
		video.put("media_id", mediaId);
		if(StringUtils.isNotBlank(title)){
			video.put("title", title);
		}
		if(StringUtils.isNotBlank(description)){
			video.put("description", description);
		}
		result.put("video", video);
		String message = JsonUtils.objectToString(result);
		return doSendMessage(appId, appSecret, message);
	}
	
	/**
	 * 发送消息并返回状态
	 * @param appId
	 * @param appSecret
	 * @param message
	 * @return -1 调用接口失败 -2 微信接口返回错误编码 0 异常 1 OK
	 */
	private static int doSendMessage(String appId, String appSecret,String message) {
		System.out.println("message="+message);
		String accessToken = WeixinUtils.getAccessToken(appId, appSecret);
		PostMethod postMethod = new PostMethod(WeixinConstants.URL.SEND_MESSAGE_URL+accessToken);
		RequestEntity  requestEntity = null;
		try{
			requestEntity = new StringRequestEntity(message,CommonConstants.CONTENT_TYPE.JSON_TYPE ,CommonConstants.ENCODE.UTF_8); 
			postMethod.setRequestEntity(requestEntity);  
			HttpClient httpclient = HttpHelper.getHttpClient();
			 int statusCode = httpclient.executeMethod(postMethod);
			 if (statusCode != HttpStatus.SC_OK) {
		    	 logger.error("sendMessage error accessToken={} message={}",accessToken,message);
		    	 return -1;
		    }
			String sendResult = postMethod.getResponseBodyAsString();
			WeixinResult result = JsonUtils.jsonToObject(WeixinResult.class, sendResult);
			if(result.getErrcode()!=0){
				logger.error("sendMessage return error errorCode={} errmsg={} appId={} appSecret={} message={}",new Object[]{result.getErrcode(),result.getErrmsg(),appId,appSecret,message});
				return -2;
			}
			return 1;
		}catch(Exception e){
			logger.error("sendWeixinMessage Exception appId="+appId+",appScret="+appSecret+",message="+message,e);
			return 0;
		}finally{
			if(postMethod!=null){
				postMethod.releaseConnection();
			}
		}
	}
	
	public static List<SendArticle> getArticles(List<SendWeixinMessageDetail> swmdList,String imgRoot){
		List<SendArticle> list=Lists.newArrayList();
		for(SendWeixinMessageDetail swmd : swmdList){
			SendArticle sendArticle=new SendArticle();
			sendArticle.setTitle(swmd.getTitle());
			sendArticle.setPicurl(imgRoot+swmd.getImg());
			sendArticle.setUrl(swmd.getUrl());
			sendArticle.setDescription(swmd.getContent());
			list.add(sendArticle);
		}
		return list;
	}
}
